(function () {
	var myApp = angular.module('myApp');

	myApp.run(function ($rootScope, $q, mtAjax) {
		$rootScope.pub = {};

		mtAjax("/scheduling/api/pub/system").then(function (data) {
			$rootScope.pub.system = data[0][0];
		});

		mtAjax("/scheduling/api/pub/user").then(function (data) {
			$rootScope.pub.user = data[0][0];
		});

		mtAjax("/scheduling/api/pub/site").then(function (data) {
			$rootScope.pub.site = data[0][0];
			document.title = data[0][0].dm_descr;
		});

		mtAjax("/scheduling/api/pub/newmenulist").then(function (rs) {
			var list = rs[0];
			var level = 1;
			var root = { groups: [], items: [] };
			for (var i = 0; i < list.length; ++i) {
				var item = list[i];
				if (item.parent_id === null)
					root.groups.push($.extend(item, { groups: [], items: [] }));
			}
			
			for (var i = 0; i < list.length; ++i) {
				var item = list[i];
				if (item.parent_id === null)
					continue;
				
				for (var j = 0; j < root.groups.length; ++j) {
					if (root.groups[j].group_id === item.parent_id) {
						(item.uri.substr(0,3) == '../') && (item.uri = '/scheduling/page/' + item.uri.substr(3));
						root.groups[j].items.push(item);
						break;
					}
				}
			}
			
			$rootScope.pub.menu = root;
		});
		
		$rootScope.$on("load.url", function (event, element, url) {
			/*
			var href = location.href;
			$("nav.navbar a").each(function (index, element) {
				if (href == $(element).prop('href')) {
					$(element).parents(".dropdown").addClass("active");
					$rootScope.$watch('pub.system', function (newVal, oldVal) {
						document.title = newVal && newVal.name + '-' + $(element).text();
					});

					return false;
				}
			});
			*/
			
			/* Sidebar Menu active class */
			$(function activeCurrentPage() {
			    var url = window.location;
			    //$('#sidebar-menu a[href="' + url + '"]').parent('li').addClass('current-page');
			    var cp = $('#sidebar-menu a').filter(function () {
			        return this.href == url;
			    }).parent('li').addClass('current-page').parent('ul').slideDown().parent().addClass('active');
			    
			    cp.length || setTimeout(activeCurrentPage, 500);
			});

		});

		/*
		getMenu().then(function (data) {
			$rootScope.pub.menu = data;
		});

		function getMenu(parent_id) {
			var deferred = $q.defer();

			mtAjax("/scheduling/api/pub/menu", { parent_id: parent_id }).then(function (data) {
				var groups = data[0];
				var items = data[1];

				var deferreds = [];
				for (var i in groups)
					deferreds.push(getMenu(groups[i].group_id));

				$q.all(deferreds).then(function (data) {
					for (var i in groups)
						$.extend(groups[i], data[i]);

					deferred.resolve({ groups: groups, items: items });
				});
			});

			return deferred.promise;
		}
		*/
	});

})();
